import { Injectable, BadRequestException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import {
  ArticlesListQueryDto,
  ArticlesListResponseDto,
  ArticleDetailDto,
  SortBy,
} from './dto/articles.dto';

@Injectable()
export class ArticlesService {
  constructor(private prisma: PrismaService) {}

  /**
   * 获取文章列表
   */
  async getArticlesList(
    query: ArticlesListQueryDto,
  ): Promise<ArticlesListResponseDto> {
    const {
      page = 1,
      pageSize = 20,
      categoryId,
      status,
      keyword,
      sortBy = SortBy.LATEST,
    } = query;

    // 构建查询条件
    const where: any = {
      status: 'PUBLISHED', // 只显示已发布的文章
    };

    if (categoryId) {
      where.categoryId = categoryId;
    }

    if (status) {
      where.status = status;
    }

    if (keyword) {
      where.OR = [
        { title: { contains: keyword, mode: 'insensitive' } },
        { summary: { contains: keyword, mode: 'insensitive' } },
        { content: { contains: keyword, mode: 'insensitive' } },
      ];
    }

    // 构建排序条件
    let orderBy: any = {};
    switch (sortBy) {
      case SortBy.LATEST:
        orderBy = { createdAt: 'desc' };
        break;
      case SortBy.POPULAR:
        orderBy = { viewCount: 'desc' };
        break;
      case SortBy.VIEW_COUNT:
        orderBy = { viewCount: 'desc' };
        break;
      case SortBy.LIKE_COUNT:
        orderBy = { likeCount: 'desc' };
        break;
      default:
        orderBy = { createdAt: 'desc' };
    }

    // 查询总数
    const total = await this.prisma.article.count({ where });

    // 查询文章列表
    const articles = await this.prisma.article.findMany({
      where,
      include: {
        category: {
          select: {
            id: true,
            name: true,
          },
        },
        author: {
          select: {
            id: true,
            nickname: true,
            avatar: true,
          },
        },
      },
      orderBy,
      skip: (page - 1) * pageSize,
      take: pageSize,
    });

    // 转换为DTO格式
    const list = articles.map((article) => ({
      id: article.id,
      title: article.title,
      summary: article.summary || undefined,
      coverUrl: article.coverUrl || undefined,
      viewCount: article.viewCount,
      likeCount: article.likeCount,
      commentCount: article.commentCount,
      status: article.status,
      category: article.category,
      author: {
        ...article.author,
        avatar: article.author.avatar || undefined,
      },
      createdAt: article.createdAt.toISOString(),
      updatedAt: article.updatedAt.toISOString(),
    }));

    return {
      list,
      pagination: {
        page,
        pageSize,
        total,
        totalPages: Math.ceil(total / pageSize),
      },
    };
  }

  /**
   * 获取文章详情
   */
  async getArticleDetail(id: number): Promise<ArticleDetailDto> {
    const article = await this.prisma.article.findUnique({
      where: { id },
      include: {
        category: {
          select: {
            id: true,
            name: true,
            description: true,
          },
        },
        author: {
          select: {
            id: true,
            nickname: true,
            avatar: true,
            bio: true,
          },
        },
      },
    });

    if (!article) {
      throw new BadRequestException('文章不存在');
    }

    // 增加浏览次数
    await this.prisma.article.update({
      where: { id },
      data: { viewCount: { increment: 1 } },
    });

    return {
      id: article.id,
      title: article.title,
      summary: article.summary || undefined,
      content: article.content,
      coverUrl: article.coverUrl || undefined,
      viewCount: article.viewCount + 1, // 返回更新后的浏览次数
      likeCount: article.likeCount,
      commentCount: article.commentCount,
      status: article.status,
      category: {
        ...article.category,
        description: article.category.description || undefined,
      },
      author: {
        ...article.author,
        avatar: article.author.avatar || undefined,
        bio: article.author.bio || undefined,
      },
      createdAt: article.createdAt.toISOString(),
      updatedAt: article.updatedAt.toISOString(),
    };
  }

  /**
   * 获取文章分类列表
   */
  async getCategories() {
    const categories = await this.prisma.articleCategory.findMany({
      where: { isEnabled: true },
      select: {
        id: true,
        name: true,
        description: true,
        sort: true,
        parentId: true,
        _count: {
          select: {
            articles: {
              where: { status: 'PUBLISHED' },
            },
          },
        },
      },
      orderBy: { sort: 'asc' },
    });

    return categories.map((category) => ({
      id: category.id,
      name: category.name,
      description: category.description,
      sort: category.sort,
      parentId: category.parentId,
      articleCount: category._count.articles,
    }));
  }
}
